﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;
//using Microsoft.AspNet.Identity;
using NestedHtmlWriter;
using ANGFSessionWrapper;
using ANGFLib;

namespace AngfWebPlayer3.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var session = (MySession)Session["mysession"];
            if( session != null && session.WrappedWorkerAppDomain != null)
            {
                // fill it later!!!!!
                //session.WrappedWorkerAppDomain.SetUserId(User.Identity.GetUserId());
            }
            if (Request["start"] != null) startupSub(Request["start"]);
            else if (Request["ButtonID"] != null)
            {
                int n;
                int.TryParse(Request["ButtonID"], out n);
                session.SimpleMenuResult = n;
                session.WrappedWorkerAppDomain.ClearRenderingQueue();
                session.WrappedWorkerAppDomain.ContinueEventSet();
            }
            else if (Request["IDONLYTEXT"] != null)
            {
                //if (text.Text.Trim().Length == 0) return;
                session.SimpleStringResult = Request["IDONLYTEXT"];
                session.WrappedWorkerAppDomain.ClearRenderingQueue();
                session.WrappedWorkerAppDomain.ContinueEventSet();
            }
            var writer = new StringWriter();
            if (session.WrappedWorkerAppDomain.ScenarioThreadIsActive)
            {
                session.WrappedWorkerAppDomain.WaitAskForUserEvent();
                rebuildGamePage(writer);
            }
            else
            {
                RawMyXmlDoc[] list = session.WrappedWorkerAppDomain.StartModules();
                foreach (var s in list)
                {
                    var id = s.id;
                    using (var li = new NhLiInline(writer, null))
                    {
                        li.WriteAText("/Home/?start=" + HttpUtility.UrlEncode(id), s.name);
                    }
                }
            }
            ViewBag.MyPageData = writer.ToString();
            return View();
        }

        private void rebuildGamePage(TextWriter writer)
        {
            var session = (MySession)Session["mysession"];
            var renderingQueue = session.WrappedWorkerAppDomain.GetWaitForReady();

            foreach (var item in renderingQueue)
            {
                if (item is QueueMessage)
                {
                    var msg = item as QueueMessage;
                    System.Drawing.Color textColor = msg.MessageColor;
                    System.Drawing.Color nameColor = ANGFLib.Util.CalcCenterColor(textColor, System.Drawing.Color.Black);
                    if (msg.IsDokuhaku)
                    {
                        writer.Write("<span class='talkDokuhaku' style='color:#"
                             + string.Format("{0:X2}{1:X2}{2:X2}", textColor.R, textColor.G, textColor.B)
                             + "'>"
                             + HttpUtility.HtmlEncode(msg.Message)
                            + "</span><br />");
                    }
                    else
                    {
                        writer.Write("<table><td><span class='talkName' style='color:#"
                             + string.Format("{0:X2}{1:X2}{2:X2}", nameColor.R, nameColor.G, nameColor.B)
                             + "'>"
                             + HttpUtility.HtmlEncode(msg.MyName)
                             + "</span><span class='talkSep'>:</span></td><td><span class='talkBody' style='color:#"
                             + string.Format("{0:X2}{1:X2}{2:X2}", textColor.R, textColor.G, textColor.B)
                             + "'>"
                             + HttpUtility.HtmlEncode(msg.Message)
                            + "</span></td></table>");
                    }
                }
                else if (item is QueueSimpleMenu)
                {
                    var menu = item as QueueSimpleMenu;
                    writer.Write("<p class='menuHeader'>" + HttpUtility.HtmlEncode(menu.Prompt) + "</p>");
                    foreach (var item2 in menu.Items.Select((c, n) => new { c, n }))
                        createButton(item2.c.Name, item2.n, writer);
                    if (menu.SystemMenu != null) createButton(menu.SystemMenu.Name, -1, writer);
                }
                else if (item is QueueSimpleInputString)
                {
                    var menu = item as QueueSimpleInputString;
                    writer.Write("<p class='menuHeader'>" + HttpUtility.HtmlEncode(menu.Prompt) + "</p>");
                    writer.Write("<form method='post' action='/Home/'>");
                    writer.Write("<input type='text' name='IDONLYTEXT' value='" + HttpUtility.HtmlAttributeEncode(menu.DefaultValue) + "' />");
                    writer.Write("<input type='submit' value='送信' data-theme='c' />");
                    writer.Write("<input type='reset' value='取り消し' data-theme='c' />");
                    writer.Write("</form>");
                }
                // TBW
            }
            //var mysession = (MySession)Session["mysession"];
            //mysession.ContinueEvent.Set();
        }
        private void createButton(string caption, int resultNumber, TextWriter writer)
        {
            using (var li = new NhLiInline(writer, null))
            {
                li.WriteAText("/Home/?ButtonID=" + HttpUtility.UrlEncode(resultNumber.ToString()), caption);
            }
        }

        private void startupSub(string id)
        {
            var session = (MySession)Session["mysession"];
            session.WrappedWorkerAppDomain.StartupSub(id);
        }

        public ActionResult Player()
        {
            ViewBag.MyPageData = "TBW";
            return View();
        }

        public ActionResult addModule()
        {
            ViewBag.MyPageData = "TBW";
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        public ActionResult MaintMain()
        {
            return View();
        }

    }
}
